from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from .serializers import SPUSerializer, BrandSerializer, CategoriesSerializer
from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.utils import MyNumbPage, upload_image
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings


class SPUViewSet(ModelViewSet):
    serializer_class = SPUSerializer
    queryset = SPU.objects.all()
    pagination_class = MyNumbPage


class BrandsSimple(ListAPIView):
    serializer_class = BrandSerializer
    queryset = Brand.objects.all()


class CategoriesViewSet(ReadOnlyModelViewSet):
    serializer_class = CategoriesSerializer

    def get_queryset(self):
        pk = self.kwargs.get('pk', None)
        if pk:
            return GoodsCategory.objects.get(id=pk).subs
        else:
            return GoodsCategory.objects.all()

    def retrieve(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


class GoodsImagesView(APIView):
    def post(self, request):
        # 获取参数
        img = request.data.get('image')
        img_url = settings.BASE_URL + upload_image(img)
        if not img_url:
            return Response(status=400)
        return Response({'img_url': img_url})
